package com.newlink.building.userinfo.activity

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.constant.Base_RouterPath
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.Base_ChangePasswordBean
import com.newlink.building.common_base.utils.RegexUtils
import com.newlink.building.manager.Module_Phone_VoipController
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.databinding.ActivityAccountInformationChangePasswordBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_AccountInformationChangePasswordPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_AccountInformationChangePasswordContract
import com.newlink.building.crypt.library_crypt.digest.Md5Crypt
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker

/**
 * @author wangyang
 * @date 2022/10/26
 * @description 我的——账户信息——修改密码页面
 */
class Module_UserInfo_AccountInformationChangePasswordActivityNL :
    NL_BaseMvpActivity<Module_UserInfo_AccountInformationChangePasswordContract.View, Module_UserInfo_AccountInformationChangePasswordContract.Presenter>(),
    Module_UserInfo_AccountInformationChangePasswordContract.View, View.OnClickListener {

    var isShowOldPassword = false
    var isShowNewPassword = false
    var isShowNewPasswordAgain = false

    //    override fun attachLayoutRes(): Int = R.layout.activity_account_information_change_password
    private lateinit var mBinding: ActivityAccountInformationChangePasswordBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityAccountInformationChangePasswordBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
    }

    override fun initView() {
        super.initView()
        // 修改密码页面初始化时的混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("AccountInformationChangePasswordActivity", "initView")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom("change_password")

        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.account_information_change_password)

        mBinding.ibEye.isEnabled = false
        mBinding.linearPwdDisplay.setOnClickListener {
            val isEnable = mBinding.ibEye.isEnabled
            mBinding.etOldPassword.transformationMethod =
                if (isEnable) PasswordTransformationMethod.getInstance() else HideReturnsTransformationMethod.getInstance()
            mBinding.etNewPassword.transformationMethod =
                if (isEnable) PasswordTransformationMethod.getInstance() else HideReturnsTransformationMethod.getInstance()
            mBinding.etNewPasswordAgain.transformationMethod =
                if (isEnable) PasswordTransformationMethod.getInstance() else HideReturnsTransformationMethod.getInstance()
            mBinding.ibEye.isEnabled = !isEnable
        }

        mBinding.ivShowOldPassword.setOnClickListener(this)
        mBinding.ivShowNewPassword.setOnClickListener(this)
        mBinding.ivShowNewPasswordAgain.setOnClickListener(this)
        mBinding.btnChange.setOnClickListener(this)

        //旧密码的输入框监听
        mBinding.etOldPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkChangeButtonState()
            }

        })
        //新密码的输入框监听
        mBinding.etNewPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkChangeButtonState()
            }

        })
        //再次输入的新密码的输入框监听
        mBinding.etNewPasswordAgain.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkChangeButtonState()
            }

        })
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_show_old_password -> {
                //显示/隐藏旧密码
//                isShowOldPassword = !isShowOldPassword
//                mBinding.etOldPassword.transformationMethod =
//                    if (isShowOldPassword) HideReturnsTransformationMethod.getInstance() else PasswordTransformationMethod.getInstance()
//
//                if (isShowOldPassword) {
//                    mBinding.ivShowOldPassword.setImageResource(R.mipmap.password_show)
//                } else {
//                    mBinding.ivShowOldPassword.setImageResource(R.mipmap.password_hidden)
//                }
//                mBinding.etOldPassword.setSelection(mBinding.etOldPassword.text.length)
                mBinding.etOldPassword.text.clear()
            }

            R.id.iv_show_new_password -> {
                mBinding.etNewPassword.text.clear()
                //显示/隐藏新密码
//                isShowNewPassword = !isShowNewPassword
//                mBinding.etNewPassword.transformationMethod =
//                    if (isShowNewPassword) HideReturnsTransformationMethod.getInstance() else PasswordTransformationMethod.getInstance()
//
//                if (isShowNewPassword) {
//                    mBinding.ivShowNewPassword.setImageResource(R.mipmap.password_show)
//                } else {
//                    mBinding.ivShowNewPassword.setImageResource(R.mipmap.password_hidden)
//                }
//                mBinding.etNewPassword.setSelection(mBinding.etNewPassword.text.length)
            }

            R.id.iv_show_new_password_again -> {
                mBinding.etNewPasswordAgain.text.clear()
                //显示/隐藏再次输入的新密码
//                isShowNewPasswordAgain = !isShowNewPasswordAgain
//                mBinding.etNewPasswordAgain.transformationMethod =
//                    if (isShowNewPasswordAgain) HideReturnsTransformationMethod.getInstance() else PasswordTransformationMethod.getInstance()
//
//                if (isShowNewPasswordAgain) {
//                    mBinding.ivShowNewPasswordAgain.setImageResource(R.mipmap.password_show)
//                } else {
//                    mBinding.ivShowNewPasswordAgain.setImageResource(R.mipmap.password_hidden)
//                }
//                mBinding.etNewPasswordAgain.setSelection(mBinding.etNewPasswordAgain.text.length)
            }

            R.id.btn_change -> {
                //修改密码
                val inputOldPassword = mBinding.etOldPassword.text.trim().toString()
                val inputNewPassword = mBinding.etNewPassword.text.trim().toString()
                val inputNewPasswordAgain = mBinding.etNewPasswordAgain.text.trim().toString()

                if (inputNewPassword.length !in 8..36) {
                    showToast(getString(R.string.account_information_change_password_rules))
                    return
                }

                if (!RegexUtils.checkPassword(inputNewPassword)) {
                    showToast(getString(R.string.account_information_change_password_rules))
                    return
                }
                if (inputNewPassword != inputNewPasswordAgain) {
                    showConfirmPasswordError(true)
//                    showToast(getString(R.string.account_information_change_password_confirmation))
                    return
                }
                val changePasswordBean = Base_ChangePasswordBean()
                changePasswordBean.id = userId
//                changePasswordBean.oldPwd = Base64.encode(inputOldPassword.toByteArray())
//                changePasswordBean.firstNewPwd = Base64.encode(inputNewPassword.toByteArray())
//                changePasswordBean.secondNewPwd = Base64.encode(inputNewPasswordAgain.toByteArray())

                changePasswordBean.oldPwd = Md5Crypt.md5(inputOldPassword)
                changePasswordBean.firstNewPwd = Md5Crypt.md5(inputNewPassword)
                changePasswordBean.secondNewPwd = Md5Crypt.md5(inputNewPasswordAgain)

                mPresenter?.changePassword(accessToken, changePasswordBean)
            }
        }
    }

    fun showConfirmPasswordError(showError: Boolean) {
        mBinding.linearPwdDifferent.visibility = if (showError) View.VISIBLE else View.GONE
        mBinding.linearPwdRule.visibility = if (showError) View.GONE else View.VISIBLE
        mBinding.viewLine1.background =
            if (showError) ContextCompat.getDrawable(
                this,
                R.color.red
            ) else ContextCompat.getDrawable(this, R.color.color_e2e2e8)
        mBinding.viewLine2.background = if (showError) ContextCompat.getDrawable(
            this,
            R.color.red
        ) else ContextCompat.getDrawable(this, R.color.color_e2e2e8)
        mBinding.viewLine3.background = if (showError) ContextCompat.getDrawable(
            this,
            R.color.red
        ) else ContextCompat.getDrawable(this, R.color.color_e2e2e8)
    }

    /**
     * 修改按钮的状态
     */
    fun checkChangeButtonState() {
        showConfirmPasswordError(false)
        val inputOldPassword = mBinding.etOldPassword.text.trim().toString()
        val inputNewPassword = mBinding.etNewPassword.text.trim().toString()
        val inputNewPasswordAgain = mBinding.etNewPasswordAgain.text.trim().toString()

        mBinding.ivShowOldPassword.visibility =
            if (inputOldPassword.isNotEmpty()) View.VISIBLE else View.GONE
        mBinding.ivShowNewPassword.visibility =
            if (inputNewPassword.isNotEmpty()) View.VISIBLE else View.GONE
        mBinding.ivShowNewPasswordAgain.visibility =
            if (inputNewPasswordAgain.isNotEmpty()) View.VISIBLE else View.GONE

        mBinding.btnChange.isEnabled =
            inputOldPassword.isNotEmpty() && inputNewPassword.isNotEmpty() && inputNewPasswordAgain.isNotEmpty()
//                    && inputNewPassword == inputNewPasswordAgain
    }

    override fun createPresenter(): Module_UserInfo_AccountInformationChangePasswordContract.Presenter =
        Module_UserInfo_AccountInformationChangePasswordPresenter()

    override fun changePasswordSuccess() {
        showToast(getString(R.string.account_information_change_password_success))
        val inputNewPassword = mBinding.etNewPassword.text.trim().toString()
        pwdSaved = Md5Crypt.md5(inputNewPassword)

        ARouter.getInstance().build(Base_RouterPath.PATH_LOGIN)
            .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
            .withAction(Base_Constant.ACCOUNT_INFORMATION_CHANGE_PASSWORD)
            .navigation()
        Module_Phone_VoipController.get().delete()
        isLogin = false
    }

    override fun changePasswordFail(reason: String?) {
        showToast(getString(R.string.default_change_fail))
    }
}